package com.wonders;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


@WebServlet(value = "/AsyncServlet4", asyncSupported = true)
public class AsyncServlet4 extends HttpServlet {
    ExecutorService executorService = Executors.newFixedThreadPool(10);

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        out.append("主线程开始运行<br>");
        AsyncContext asyncContext = req.startAsync();

        asyncContext.setTimeout(1); // 设置超时要在其启动之前

        executorService.submit(new Task2(asyncContext));
        out.append("主线程运行结束<br>");
        out.append("任务执行完成，请到<a href='async.jsp'>这里</a>查看");
    }

    @Override
    public void destroy() {
        executorService.shutdown();
    }
}
